package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.OrderBatch;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.service.OrderBatchService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class CmdEnd extends AbstractCmd {

    @Resource
    private GroupService groupService;
    @Resource
    private OrderBatchService orderBatchService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        Long chatId = update.getMessage().getChatId();
        List<Group> groups = groupService.lambdaQuery()
                .eq(Group::getTgGroupId, chatId)
                .list();
        if (CollectionUtils.isEmpty(groups)) {
            RobotUtils.sendText(chatId, "群未在系统维护，开启群账单失败！", bot);
        }
        Group group = groups.get(0);
        if (!Boolean.TRUE.equals(group.getBatchStatus())) {
            RobotUtils.sendText(chatId, "记账未开启，无需完成！", bot);
            return;
        }
        group.setBatchStatus(false);
        groupService.updateById(group);
        List<OrderBatch> list = orderBatchService.lambdaQuery()
                .eq(OrderBatch::getBatchId, group.getBatchId())
                .list();
        for (OrderBatch orderBatch : list) {
            orderBatch.setEndTime(new Date());
        }
        if (!CollectionUtils.isEmpty(list)) {
            orderBatchService.updateBatchById(list);
        }
        RobotUtils.sendText(chatId, "本批次记账已完成！", bot);
    }

    @Override
    public String getCmdName() {
        return "结束";
    }

    @Override
    public String getDescribe() {
        return "结束                           结束记账批次\n";
    }
}
